package com.iwown.sample4GApi.controller;

import com.google.gson.Gson;
import com.iwown.sample4GApi.domain.ResponseObject;
import com.iwown.sample4GApi.domain.ResponseWithData;
import com.iwown.sample4GApi.domain.SleepResult;
import com.iwown.sample4GApi.utils.MyDateTimeUtils;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@RequestMapping("/health")
public class SleepController {

    private static final Logger log = LoggerFactory.getLogger(SleepController.class);
    private static final Gson gson = new Gson();

    @RequestMapping(value = "sleep", method = RequestMethod.GET)
    public String getSleepResult(
            @RequestParam(required = true) String deviceid,
            @RequestParam(required = true) String sleep_date) {

        if(TextUtils.isEmpty(deviceid) || !MyDateTimeUtils.isValidDate(sleep_date)){
            ResponseObject respObj = new ResponseObject();
            respObj.setReturnCode(10002);
            return gson.toJson(respObj);
        }
        log.info(String.format("getSleepResult %s %s",deviceid,sleep_date));
        //check whether there is sleep data available with specified deviceid/sleepdata
        boolean dataExist = true;
        if(dataExist) {
            ResponseWithData responseData = new ResponseWithData();
            responseData.setReturnCode(0);
            SleepResult sleep = new SleepResult();
            sleep.setDeviceid(deviceid);
            String prev_day = MyDateTimeUtils.getPreviousDay(sleep_date);
            sleep.setSleep_date(sleep_date);
            //the sleep data here is get by invoke algorithm api to calculate sleep result
            //see doc here : https://api8.iwown.com/iot_platform/calculation.html#id4
            sleep.setStart_time(prev_day + " 23:15:00");
            sleep.setEnd_time(sleep_date + " 07:00:00");
            sleep.setDeep_sleep(85);
            sleep.setLight_sleep(300);
            sleep.setWeak_sleep(30);
            sleep.setEyemove_sleep(50);
            sleep.setScore(80);
            sleep.setOsahs_risk(0);
            sleep.setSpo2_score(0);
            sleep.setSleep_hr(60);
            responseData.setData(sleep);
            return gson.toJson(responseData);
        } else {
            ResponseObject respObj = new ResponseObject();
            respObj.setReturnCode(10404);
            return gson.toJson(respObj);
        }
    }


}
